<?php

	namespace app\test\controller;

	use app\admin\behavior\Workteam;
	use app\admin\model\facrm\Customer;
	use app\admin\model\facrm\Record;
	use app\admin\model\facrm\record\Files;
	use app\admin\model\workteam\Log;
	use app\admin\model\workteam\Project;
	use app\admin\model\workteam\Task;
	use app\common\model\Area;
	use app\test\model\Admin;
	use app\test\model\FacrmCustomer;
	use app\test\model\FacrmCustomerContacts;
	use app\test\model\FacrmRecord;
	use app\test\model\Family;
	use app\test\model\FamilyUser;
	use app\test\model\SurveyRecords;
	use app\test\model\SystemAdmin;
	use app\test\model\User;
	use EasyWeChat\Factory;
	use EasyWeChatComposer\EasyWeChat;
	use fast\Date;
	use fast\Form;
	use fast\Random;
	use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
	use think\Controller;
	use think\Db;

	class Index extends Controller{
		public function index(){
			exit();
			hook('memory');
		}

		public function serviceLogC(){
			$this->serviceLog();
			echo '执行完毕，手动处理workteam_log表里的数据';
		}

		protected function importRecord(){
			$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
			$PHPExcel = $reader->load('record.xlsx');

			$currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
			$allRow = $currentSheet->getHighestRow(); //取得一共有多少行
			$datas = [];

			for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
				$customer_id = $currentSheet->getCellByColumnAndRow(2, $currentRow)->getValue();
				$time_text = $currentSheet->getCellByColumnAndRow(3, $currentRow)->getFormattedValue();
				$time = strtotime($time_text) ?: 0;
				$admin_name = $currentSheet->getCellByColumnAndRow(4, $currentRow)->getFormattedValue();
				switch($admin_name){
					case '胡雯雯':$admin_id = 3;break;
					case '任晓峰':$admin_id = 2;break;
					case '许孝随':$admin_id = 4;break;
					case 'Admin':$admin_id = 1;break;
				}
				$content = $currentSheet->getCellByColumnAndRow(6, $currentRow)->getFormattedValue();
				if($content != ''){
					$datas[] = [
						'types' => 'customer',
						'types_id' => $customer_id,
						'content' => $content,
						'content_text' => $content,
						'record_type' => 1,
						'service_time' => $time,
						'create_time' => $time,
						'create_user_id' => $admin_id,
					];
				}
			}

			Db::execute('TRUNCATE TABLE eb_facrm_record');
			Db::name('facrm_record')->insertAll($datas);
		}

		protected function serviceLog(){
			Db::execute("TRUNCATE TABLE eb_service_log");
			Db::execute("TRUNCATE TABLE eb_service_log_files");

			$projectModel = new Project();
			$workteamLogModel = new Log();

			$records = Db::name('facrm_record0')->select();
			foreach($records as $record){
				$project = $projectModel->where(['customer_id'=>$record['types_id'], 'delete_time' => null])->order('id asc')->find();
				$project_id = $project ? $project->id : 0;
				$data = [
					'customer_id' => $record['types_id'],
					'project_id' => $project_id,
					'task_id' => 0,
					'service_client' => $record['service_client'],
					'service_time' => $record['service_time'],
					'content' => $record['content'],
					'content_text' => $record['content_text'],
					'secret' => $record['content'],
					'secret_text' => $record['content_text'],
					'create_user_id' => $record['create_user_id'],
					'create_time' => $record['create_time'],
					'update_time' => $record['update_time'],
					'delete_time' => $record['delete_time'],
				];
				$log_id = Db::name('service_log')->insertGetId($data);

				$filesData = [];
				$files = Db::name('facrm_record_files0')->where(['record_id' => $record['id']])->select();
				foreach($files as $file){
					$filesData[] = [
						'log_id' => $log_id,
						'url' => $file['url'],
						'create_time' => $file['create_time'],
					];
				}
				Db::name('service_log_files')->insertAll($filesData);
			}

			/*$logDatas = [];
			$workteamLogs = $workteamLogModel->where(['create_type' => 1])->select();
			foreach($workteamLogs as $log){
				$project = $projectModel->where(['id' => $log->project_id])->find();
				$logDatas[] = [
					'customer_id' => $project->customer_id,
					'project_id' => $log->project_id,
					'task_id' => $log->task_id,
					'service_client' => $log->service_client,
					'service_time' => $log->create_time,
					'content' => $log->title,
					'content_text' => $log->title,
					'secret' => $log->content,
					'secret_text' => $log->content_text,
					'create_user_id' => $log->admin_id,
					'create_time' => $log->create_time,
					'update_time' => $log->create_time,
					'delete_time' => null,
				];
			}
			Db::name('service_log')->insertAll($logDatas);*/
		}

		public function getUnionid(){
			$config = [
				    'app_id' => 'wx5a5e6b539b2da70e',
					'secret' => '6ccc009958d28cc69f077c768135ead6',
					'token' => 'wenxinyige',
					'response_type' => 'array',
			];
			$app = Factory::officialAccount($config);

			$user1 = Db::name('wechat_user')->select();
			foreach($user1 as $user){
				$wxuser = $app->user->get($user['openid']);
				if(isset($wxuser['unionid'])) Db::name('wechat_user')->where('id','=',$user['id'])->update(['unionid'=>$wxuser['unionid']]);
			}
		}

		public function surveyCount(){
			$customer = Customer::all();
			foreach($customer as $k=>$v){
				$count = SurveyRecords::where('customer_id','=',$v['id'])->where('is_del','=',0)->count();
				Customer::where('id','=',$v['id'])->update(['survey1_count'=>$count]);
			}
		}

		public function recordContent(){
			$list = FacrmRecord::all();
			foreach($list as $record){
				$record->content_text = html_entity_decode(strip_tags($record->content));
				$record->save();
			}
		}


		public function transform(){
			$this->admin();
			$this->familyToCustomer();
			$this->userToContact();
			$this->survey();
			$this->assess();
			$this->identify();
		}

		protected function admin(){
			$adminModel = new Admin();
			$adminModel->where(['id'=>['<>',1]])->delete();
			$adminModel->query('ALTER TABLE eb_admin AUTO_INCREMENT = 1');

			$newData = [];
			$old = SystemAdmin::where(['id'=>['<>','1']])->select();
			foreach($old as $k=>$v){
				$newData[] = [
					'id' => $v['id'],
					'username' => $v['account'],
					'nickname' => $v['real_name'],
					'password' => '5c61fe43038639d806bdefb7991dbff0',
					'salt' => 'f75184',
					'avatar' => '/assets/img/avatar.png',
					'email' => $v['account'].'@wenxin-yige.cn',
					'mobile' => $v['phone'],
					'logintime' => $v['last_time'],
					'loginip' => $v['last_ip'],
					'createtime' => $v['add_time'],
					'updatetime' => $v['add_time'],
					'status' => 'normal',
					'uid' => $v['uid'],
				];
			};
			$res = $adminModel->saveAll($newData, false);
			if($res) dump('admin completed');

			// eb_admin_log
			Db::query('TRUNCATE TABLE eb_admin_log');
		}
		protected function familyToCustomer(){
			// family -> customer
			$follow_statuss = [
				'意向' => '1',
				'体验中' => '2',
				'已签约' => '3',
				'服务' => '4',
				'售后' => '5',
				'中断' => '6',
			];

			$newData = [];
			$familyModel = new Family();
			$familys = $familyModel->select();
			foreach($familys as $v){
				$data = [
					'name' => $v['title'],
					'level' => $v['sort'],
					'source' => 0,
					'remark' => $v['content1'],								// 基本情况
					'owner_user_id' => $v['admin_id'],						// 负责人ID
					'owner_user_ids' => $v['admin_ids'],					// 助教ID
					'create_time' => $v['add_time'] ?: time(),				// 创建时间
					'update_time' => $v['update_time'],						// 更新时间
					'service' => $v['service'],								// 当前服务
					'keynote' => $v['keynote'],								// 近期重点
					'follow_status' => $follow_statuss[$v['stage']],		// 阶段
				];

				$areas = explode(' ',$v['area']);
				if(isset($areas[0]) && $areas[0]){
					$province = Area::where(['level'=>1,'name'=>['like','%'.$areas[0].'%']])->value('id');
					if($province) $data['province'] = $province;
				}
				if(isset($areas[1]) && $areas[1]){
					$city = Area::where(['level'=>2,'name'=>['like','%'.$areas[1].'%']])->value('id');
					if($city) $data['city'] = $city;
					if($areas[1] == '泰安') $data['spread_uid'] = 11;
				}
				if(isset($areas[2]) && $areas[2]){
					$area = Area::where(['level'=>3,'name'=>['like','%'.$areas[2].'%']])->value('id');
					if($area) $data['area'] = $area;
				}
				if($v['is_del'] == 1) $data['delete_time'] = 1;

				$newData[] = $data;
			}

			Db::query('TRUNCATE TABLE eb_facrm_customer');
			$customerModel = new FacrmCustomer();
			$res = $customerModel->saveAll($newData, false);
			if($res) dump('customer completed');
		}
		protected function userToContact(){
			$newData = [];
			$fuModel = new FamilyUser();
			$customerModel = new FacrmCustomer();

			$userModel = new User();
			$user = $userModel->select();
			foreach($user as $v){
				$fu = $fuModel->where(['uid'=>$v['uid'],'is_del'=>0])->order('id desc')->find();
				$data = [
					'customer_id' => isset($fu['family_id']) ? $fu['family_id'] : 0,		// 客户ID
					'name' => $v['nickname'],		// 姓名
					'post' => isset($fu['role']) ? $fu['role'] : '',
					'mobile' => $v['phone'],		// 手机
					'telephone' => $v['phone'],		// 电话
					'uid' => $v['uid'],		// 关联用户
					'create_time' => $v['add_time'],		// 创建时间
					'update_time' => $v['add_time'],		// 更新时间
				];
				$newData[] = $data;

				if(isset($fu['family_id'])) $customerModel->where(['id'=>$fu['family_id'],'spread_uid'=>0])->update(['spread_uid'=>$v['spread_uid']]);
			}

			Db::query('TRUNCATE TABLE eb_facrm_customer_contacts');
			$m = new FacrmCustomerContacts();
			$res = $m->saveAll($newData);
			if($res) dump('customer contacts completed');
		}
		protected function survey(){
			Db::query('UPDATE eb_survey_records SET customer_id=family_id');
		}
		protected function assess(){
			Db::query('UPDATE eb_assess_point SET customer_id=family_id');
		}
		protected function identify(){
			Db::query('UPDATE eb_oh_cards_identify SET customer_id=family_id');
		}
	}